import { fileURLToPath, URL } from 'node:url';
import type { ConfigEnv, UserConfig } from 'vite';
import { loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver, VantResolver } from 'unplugin-vue-components/resolvers';
import legacy from '@vitejs/plugin-legacy';
import dayjs from 'dayjs';
import AutoImport from 'unplugin-auto-import/vite';

const appVersion = dayjs().format('YYYYMMDDHHmmss');
// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  console.log(`=== run ${command} ${dayjs().format('YYYY-MM-DD HH:mm:ss')} ===`);
  const env = loadEnv(mode, process.cwd());
  return {
    //base: command === 'serve' ? '/shop/' : `${env.VITE_CDN_BASE_PATH}${env.VITE_OSS_BASE_PATH}${appVersion}/`,
    base: '/shop/',
    plugins: [
      vue(),
      Components({
        resolvers: [VantResolver(), ElementPlusResolver()],
      }),
      legacy({
        targets: ['chrome 52'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        renderLegacyChunks: true,
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    server: {
      host: true,
      port: 5271,
      proxy: {
        // '/dev-api': {
        //   target: 'https://api.it120.cc/xiaochengxu',
        //   changeOrigin: true,
        //   secure: false,
        //   rewrite: (path) => path.replace(/^\/dev-api/, ''),
        // },
        '^/api/*': env.VITE_SERVER_BASE_URL,
        '^/cm/*': env.VITE_SERVER_BASE_URL,
      },
    },
    build: {
      //outDir: `./dist/${appVersion}`,
      // target: 'es2015',
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
  };
};
